package common

import (
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"log"
	"time"
)

// GetJwtToken todo: 生成Token
func GetJwtToken(secretKey string, iat, seconds int64, payload string) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["payload"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

// CheckJwtToken todo:解析Token是否验证失效
func CheckJwtToken(tokenString string, payload string, key string) error {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
		hmacSampleSecret := []byte(key)
		return hmacSampleSecret, nil
	})
	//判断token解析
	if err != nil {
		log.Println("token无效!", err)
		return err
	}
	claims, _ := token.Claims.(jwt.MapClaims)
	res, _ := claims["exp"].(float64)
	//判断token过期时间
	if time.Now().Unix() > int64(res) {
		return fmt.Errorf("token已过期")
	}
	//判断token解析的ID与用户ID是否匹配
	if claims["payload"].(string) != payload {
		return fmt.Errorf("用户id无效")
	}

	return nil
}
